package jsf.uss.controllers;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import jsf.uss.data.IRepository;
import jsf.uss.factory.HibernateUtil;
import jsf.uss.models.Client;

import org.hibernate.Session;
import org.hibernate.Transaction;

public class ClientController implements IRepository<Client> {

    public Client      client;
    public Session     session;
    public Transaction transaction;

    public ClientController() {
    }

    @Override
    public List<Client> getAll() {

	List<Client> clientsList = new ArrayList<Client>();
	this.session = HibernateUtil.getSessionFactory().openSession();
	this.transaction = session.beginTransaction();
	clientsList = castList(Client.class,
		this.session.createCriteria(Client.class).list());
	this.transaction.commit();
	this.session.flush();
	this.session.close();

	return clientsList;
    }

    @Override
    public Client getById(Long id) {
	this.session = HibernateUtil.getSessionFactory().openSession();
	this.transaction = session.beginTransaction();
	this.client = (Client) session.get(Client.class, id);
	this.transaction.commit();
	this.session.close();

	return client;
    }

    @Override
    public boolean add(Client entity) {
	if (entity != null) {
	    this.session = HibernateUtil.getSessionFactory().openSession();
	    this.transaction = session.beginTransaction();
	    this.session.save(entity);
	    this.transaction.commit();
	    this.session.close();

	    return true;
	}
	else {
	    return false;
	}
    }

    @Override
    public boolean update(Client entity) {
	if (entity != null) {
	    this.session = HibernateUtil.getSessionFactory().openSession();
	    this.transaction = session.beginTransaction();
	    this.session.update(entity);
	    this.transaction.commit();
	    this.session.close();

	    return true;
	}
	else {
	    return false;
	}
    }

    @Override
    public boolean remove(Long id) {
	Client client = (Client) session.get(Client.class, id);

	if (client != null) {
	    this.session = HibernateUtil.getSessionFactory().openSession();
	    this.transaction = session.beginTransaction();
	    this.session.delete(client);
	    this.transaction.commit();
	    this.session.close();

	    return true;
	}
	else {
	    return false;
	}
    }

    @Override
    public boolean remove(Client entity) {
	if (entity != null) {
	    this.session = HibernateUtil.getSessionFactory().openSession();
	    this.transaction = session.beginTransaction();
	    this.session.delete(entity);
	    this.transaction.commit();
	    this.session.close();

	    return true;
	}
	else {
	    return false;
	}
    }

    public static <T> List<T> castList(Class<? extends T> clazz, Collection<?> c) {
	List<T> r = new ArrayList<T>(c.size());
	for (Object o : c)
	    r.add(clazz.cast(o));
	return r;
    }

}
